<?php
/*
 * Copyright (c) 2022.  Liuhongbin All rights reserved.
 * @domain http://dkyx.cc
 * @author liuhongbin <514660094@qq.com>
 */

namespace app\common\model\wework;

use hiduoke\services\facade\WorkWechatService;

/**
 * 外部客户
 * Class WeworkKfUser
 * @package app\common\model\wework
 * User: liuhongbin
 * Date: 2022-07-20 23:33
 */
class WeworkKfUser extends WeworkBaseModel
{
    public function getKfExternalUser($external_userid, $servicer_userid, $scene = "")
    {
        $user = $this->where(['external_userid' => $external_userid, 'plaid' => get_plaid()])->findOrEmpty();
        if ($user->isEmpty()) {
            $user_res = WorkWechatService::kfBatchget($external_userid);
            if ($user_res['errcode'] == 0) {
                $customer = $user_res['customer_list'][0];
                $data = array(
                    "external_userid" => $customer['external_userid'],
                    "nickname"        => $customer['nickname'],
                    "avatar"          => $customer['avatar']??'',//第三方授权不会返回头像
                    "gender"          => $customer['gender'],
                    "servicer_userid" => $servicer_userid,
                    "scene"           => $scene,
                    "plaid"           => get_plaid()
                );
                $user->save($data);
            } else {
                return false;
            }
        } else {
            $user->servicer_userid = $servicer_userid;
            if ($scene) {
                $user->scene = $scene;
            }
            $user->save();
        }
        return $user;
    }
}
